from os import path


class FileDetect():
	def match(self, location, states):
		if path.isfile(location) is False:
			return None

		with open(location, 'r', encoding='utf-8') as file:
			lines = file.readlines()

		state_actives = [{
			'name': state['name'],
			'begin': state['begin'],
			'end': state['end'],
			'active': False,
			'searching': True,
		} for state in states]

		for line_index in range(len(lines) - 1, -1, -1):
			for state in state_actives:

				if state['searching'] is False:
					continue

				if state['end'] in lines[line_index]:
					state['active'] = False
					state['searching'] = False

				if state['begin'] in lines[line_index]:
					state['active'] = True
					state['searching'] = False

		active_states = [state for state in state_actives if state['active'] is True]

		if len(active_states) == 0:
			return None

		return active_states[0]['name']
